package com.ocrgroup.sample.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.etop.BankCard.BankCardAPI;
import com.etop.bank.activity.BankRecogActivity;
import com.etop.bank.activity.BankScanActivity;
import com.etop.bank.model.OcrKeyDatas;
import com.etop.bank.utils.BankConfig;
import com.etop.bank.utils.SDKMessageUtil;
import com.etop.bank.utils.StreamUtil;
import com.example.bank_ocr.R;
import com.ocrgroup.sample.bean.ResultListInfo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 调用银行卡识别库的示例代码
 */
public class MainActivity extends AppCompatActivity {

	//接收识别结果返回码
	private static final int RECOG_RESULT_CODE = 101;
	//进入扫描识别页面的权限码
	private static final int REQUEST_SCAN_PERMISSION = 102;
	//进入导入识别页面的权限码
	private static final int REQUEST_IMPORT_PERMISSION = 103;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		/** 进入扫描页面前必须加上，否则识别核心激活失败，返回错误码21，无法识别 **/
		StreamUtil.initLicenseFile(this, BankConfig.licenseId);
		StreamUtil.initNCFile(this, BankConfig.nc_obj_bin);
		StreamUtil.initNCFile(this, BankConfig.nc_obj_param);
		StreamUtil.initNCFile(this, BankConfig.bc_nc_bin);
		StreamUtil.initNCFile(this, BankConfig.bc_nc_dic);
		StreamUtil.initNCFile(this, BankConfig.bc_nc_param);
		// SDK版本
		TextView main_sdk_tag = findViewById(R.id.main_sdk_tag);
		main_sdk_tag.setText("SDK识别(当前版本:V" + BankCardAPI.getBankInstance().VERSION_CODE + ")");
	}

	/**
	 * 点击进入扫描银行卡识别
	 *
	 * @param view
	 */
	private boolean isVertical;
	public void scanBank(View view) {
		if (view.getId() == R.id.scan_bank_h) {
			isVertical = false;
		} else if (view.getId() == R.id.scan_bank_v) {
			isVertical = true;
		}
		//Android 6.0以上版本，权限适配
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			//检查是否有相应的权限
			if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
					&& ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
				// 有权限，启动银行卡扫描识别页面
				Intent intent = new Intent(this, BankScanActivity.class);
				intent.putExtra(OcrKeyDatas.RECOG_TYPE, isVertical);
				startActivityForResult(intent, RECOG_RESULT_CODE);
			} else {
				//没有权限申请权限
				ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,
						Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_SCAN_PERMISSION);
			}
		} else {
			//启动银行卡扫描识别页面
			Intent intent = new Intent(this, BankScanActivity.class);
			intent.putExtra(OcrKeyDatas.RECOG_TYPE, isVertical);
			startActivityForResult(intent, RECOG_RESULT_CODE);
		}
	}

	/**
	 * 点击进入导入银行卡识别
	 *
	 * @param view
	 */
	public void importBank(View view) {
		//Android 6.0以上版本，权限适配
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			//检查是否有相应的权限
			if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
				// 有权限，启动银行卡导入识别页面
				Intent intent = new Intent(this, BankRecogActivity.class);
				startActivityForResult(intent, RECOG_RESULT_CODE);
			} else {
				//没有权限申请权限
				ActivityCompat.requestPermissions(this, new String[]{
						Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_IMPORT_PERMISSION);
			}
		} else {
			//启动银行卡导入识别页面
			Intent intent = new Intent(this, BankRecogActivity.class);
			startActivityForResult(intent, RECOG_RESULT_CODE);
		}
	}

	/**
	 * 接收从 银行卡识别库 返回的识别结果
	 *
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		//返回了识别结果
		if (data != null && requestCode == RECOG_RESULT_CODE) {
			// TODO HashMap格式数据
			HashMap<String, String> hashMap = (HashMap) data.getSerializableExtra(OcrKeyDatas.RECOG_RESULT_HASHMAP);
			//  获取识别码
			int recogCode = data.getIntExtra(OcrKeyDatas.RECOG_CODE, -1);
			//接收识别的裁切图路径
			String bankPath = data.getStringExtra(OcrKeyDatas.CROP_PATH);
			//接收识别框内图路径
			String imagePath = data.getStringExtra(OcrKeyDatas.IMAGE_PATH);

			// 转为list用于数据展示
			List<ResultListInfo> listResult = new ArrayList<>();
			// 添加结果结合
			for (int i = 0; i < hashMap.size(); i++) {
				ResultListInfo resultListInfo = new ResultListInfo();
				if (recogCode == 0) {
					resultListInfo.setKey(OcrKeyDatas.BANK_NAME[i]);
					resultListInfo.setValue(hashMap.get(OcrKeyDatas.BANK_KEY[i]));
				} else {
					resultListInfo.setKey("识别失败");
					resultListInfo.setValue(hashMap.get(OcrKeyDatas.OCR_ERROR));
					listResult.add(resultListInfo);
					break;
				}
				listResult.add(resultListInfo);
			}
			// 跳转结果界面
			Intent intent = new Intent(this, OcrResultActivity.class);
			intent.putExtra(OcrKeyDatas.RECOG_RESULT_LIST, (Serializable) listResult);
			intent.putExtra(OcrKeyDatas.RECOG_CODE, recogCode);
			intent.putExtra(OcrKeyDatas.IMAGE_PATH, imagePath);
			intent.putExtra(OcrKeyDatas.CROP_PATH, bankPath);
			intent.putExtra(OcrKeyDatas.TITLE, "银行卡");
			startActivity(intent);
		} else {
			//取消了识别
		}
	}

	/**
	 * 接收 申请权限回调的 处理
	 *
	 * @param requestCode
	 * @param permissions
	 * @param grantResults
	 */
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		switch (requestCode) {
			case REQUEST_SCAN_PERMISSION:
				if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败
					Toast.makeText(this, "请允许权限在识别", Toast.LENGTH_SHORT).show();
				} else {//成功
					// 启动银行卡扫描识别页面
					Intent intent = new Intent(this, BankScanActivity.class);
					intent.putExtra(OcrKeyDatas.RECOG_TYPE, isVertical);
					startActivityForResult(intent, RECOG_RESULT_CODE);
				}
				break;
			case REQUEST_IMPORT_PERMISSION:
				if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败
					Toast.makeText(this, "请允许权限在识别", Toast.LENGTH_SHORT).show();
				} else {//成功
					// 启动银行卡导入识别页面
					Intent intent = new Intent(this, BankRecogActivity.class);
					startActivityForResult(intent, RECOG_RESULT_CODE);
				}
				break;
		}
	}

	/**
	 * 显示调试参数信息
	 */
	public void showLog(View view) {
		SDKMessageUtil.logSDKMassage(this, BankConfig.nAultType, BankConfig.licenseId,
				BankCardAPI.getBankInstance().VERSION_CODE);
		String SDKMsg = SDKMessageUtil.getSDKMassage(this, BankConfig.nAultType, BankConfig.licenseId);
		showSDKMsg(SDKMsg);
	}

	/**
	 * 显示调试信息
	 */
	private void showSDKMsg(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this).setIcon(R.mipmap.ocr_log).setTitle("相关参数")
				.setMessage(message).setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialogInterface, int i) {
						dialogInterface.dismiss();
					}
				});
		builder.create().show();
	}
}
